package com.htbb.service.personalInsure.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.htbb.common.base.PropertiesConfig;
import com.htbb.common.util.JaxbXmlUtil;
import com.htbb.common.util.MD5Util;
import com.htbb.common.util.UtilDate;
import com.htbb.model.qianhaiIsu.Body;
import com.htbb.model.qianhaiIsu.Edr;
import com.htbb.model.qianhaiIsu.Head;
import com.htbb.model.qianhaiIsu.Packet;
import com.htbb.model.qianhaiIsu.RspPacket;

/**
 * 前海-就医160停诊险接口（退保接口）
 * @author lll
 * @date 2017年9月19日14:54:58
 */
@Service
public class QHTZXPolicyService{
	private Logger logger = LoggerFactory.getLogger(QHTZXPolicyService.class);
	
	public Map<String, String> sendPolicyCancellation(String policyNo, String orderTime) {
		String errCode = "-1";
		String errMsg = "退保出现异常！";
		
		Packet packet = new Packet();
		Head head = new Head();
		packet.setHead(head);
		head.setUUID(policyNo);
		head.setCRequestType("170002"); //新版承保：170001 退保：170002
		head.setCBusiChnl(PropertiesConfig.busiChnl);
		head.setTAcctTm(orderTime); //"2017-08-22 16:10:19"
		Body body = new Body();
		packet.setBody(body);
		body.setCancleDate(UtilDate.getFormatDateString(new Date(), UtilDate.simple)); //"2017-08-22 16:10:19"
		body.setCProdNo(PropertiesConfig.prodNo);
		List<Edr> edrList = new ArrayList<>();
		body.setEdrList(edrList);
		Edr edr = new Edr();
		edrList.add(edr);
		edr.setPlyNo(policyNo);
		
		//设置head中的签名信息
		String checkCode = MD5Util.MD5Encode(PropertiesConfig.signKey + head.getUUID() + head.getCRequestType() + head.getCBusiChnl() + head.getTAcctTm() 
			+ body.getCProdNo(), "UTF-8");
		head.setCheckCode(checkCode);
		
		try{
			String sendXml = JaxbXmlUtil.convertObjectToXml(packet, null);
			logger.info("前海财险（就医160停诊险接口）退保请求：" + sendXml);
			
			String resultStr = sendWSRequest(PropertiesConfig.webServiceUrl, sendXml); //port.excute(sendXml);
			logger.info("前海财险（就医160停诊险接口）退保响应xml：" + resultStr);
			RspPacket rspPacket = JaxbXmlUtil.convertXmlToObject(resultStr, RspPacket.class);
			logger.info("前海财险（就医160停诊险接口）退保响应obj：" + rspPacket);
			
			if( rspPacket.getHead().getResultCode() != null && rspPacket.getHead().getResultCode().equals("0000")){
				logger.info("前海财险（就医160停诊险接口）退保响应成功！");
				errCode = "0";
				errMsg = "退保成功";
			}
			else{
				logger.info("前海财险（就医160停诊险接口）退保失败！");
				errCode = "-1";
				errMsg = "退保失败：" + rspPacket.getHead().getResultMessage();
			}
			
		}
		catch (JAXBException e){
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Map<String, String> retMap = new HashMap<>();
		retMap.put("retCode", errCode);
		retMap.put("retMsg", errMsg);
		return retMap;
	}
	
	public String sendWSRequest(String requestUrl, String requestStr) throws Exception{
		System.out.println("requestUrl:"+requestUrl);
		requestStr = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.agent.sunline.com/\"><soapenv:Header/><soapenv:Body><ws:excute><data><![CDATA["
					+ requestStr
					+ "]]></data></ws:excute></soapenv:Body></soapenv:Envelope>";
		String responseStr = "";
		PostMethod postmethod = new PostMethod(requestUrl);
		byte[] bRequestXml;
		try {
			bRequestXml = requestStr.getBytes("UTF-8");
			InputStream is = new ByteArrayInputStream(bRequestXml, 0, bRequestXml.length);
			RequestEntity re = new InputStreamRequestEntity(is, bRequestXml.length,
					"application/xop+xml; charset=UTF-8; type=\"text/xml\"");
			postmethod.setRequestEntity(re);
			//modify 使用统一创建HttpClient, by yangtang 2017-05-23 16:31:35
			org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
			int statusCode = httpClient.executeMethod(postmethod);// 状态预留
			if(200 != statusCode){
				throw new HttpException("请求异常，http响应码：" + statusCode);
			}
			responseStr = new String(postmethod.getResponseBody(), "UTF-8");
			responseStr = URLDecoder.decode(responseStr, "utf-8");
			responseStr = responseStr.replace("&#xD;", "").replaceAll("&lt;", "<")
					.replaceAll("&gt;", ">").replaceAll("&quot;", "\"");
			responseStr = responseStr.substring(responseStr.indexOf("<return>")+"<return>".length(),responseStr.indexOf("</return>"));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return responseStr;
	}
	
}
